package com.example.weatherdemo;

import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.function.BiConsumer;

public class NetWork extends Object {

    public interface NetWorkResult {
        public void onReceiveResult(String content);
    }

    public NetWorkResult callback = null;
    NetHandle netHandle = null;
    HttpURLConnection connection = null;
    Context context;

    public NetWork(Context context) {
        this.context = context;
        NetManager netManager = NetManager.getInstance(context);
        netHandle = netManager.getDefaultNet();
    }

    public void startRequest(String urlString, Map<String, String> headers,Map<String, String> params) {
        String string = urlString;
        for (int i = 0; i < params.keySet().toArray().length; i++) {
            if (i == 0) {
                string += "?";
            } else {
                string += "&";
            }
            String key = (String) params.keySet().toArray()[i];
            string += key + "=" + (String) params.get(key);
        }
        try {
            URL url = new URL(string);
            connection = (HttpURLConnection) netHandle.openConnection(url, java.net.Proxy.NO_PROXY);
            connection.setRequestMethod("GET");
            headers.forEach(new BiConsumer<String, String>() {
                @Override
                public void accept(String s, String s2) {
                    connection.setRequestProperty(s, s2);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        TaskDispatcher globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        Revocable revocable = globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                try {
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    byte[] data = read(inputStream);
                    String html = new String(data, "UTF-8");
                    context.getUITaskDispatcher().syncDispatch(()   -> {
                        if (callback != null) {
                            callback.onReceiveResult(html);
                        }
                    });

                } catch(Exception e) {

                }
            }

            public byte[] read(InputStream inStream) throws Exception{
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while((len = inStream.read(buffer)) != -1)
                {
                    outStream.write(buffer,0,len);
                }
                inStream.close();
                return outStream.toByteArray();
            }
        });
    }
}
